<?php
namespace Admin\Model;
class WikiModel extends \Think\Model{

    //表名
    public $tableName = 'wiki';

    //表单验证
    protected $_validate = array();

    //wiki文档目录
    public $wiki_dir;
    //wiki文档路径
    public $wiki_path;
    //默认文档后缀
    public $wiki_ext;

    public function _initialize() {
        $this->wiki_dir = C('WIKI_DIR') ? C('WIKI_DIR') : 'wiki'; //wiki文档目录
        $this->wiki_path = dirname(APP_PATH).'/'.$this->wiki_dir.'/';
        $this->wiki_ext = '.md';
    }

    //添加wiki
    public function addWiki($data = null)
    {
        if(!$data) $data = $_POST;
        $pid = (int)$data['pid'];
        $filename = trim($data['filename']);
        $title = trim($data['title']);
        $list_order = (int)$data['list_order'];
        $status = isset($data['status']) ? (int)$data['status'] : 1;
        if(empty($title)) {
            $this->error = '文档标题不能为空！';
            return false;
        }
        if($filename) {
            if (!preg_match('/\.[a-z\d]+$/i', $filename)) {
                $filename .= $this->wiki_ext;
            }
            $savefile = $this->getFilePath($this->wiki_path.$filename);
            if(file_exists($savefile)) {
                $this->error = '保存的文档名称已存在！';
                return false;
            }
            $r = file_put_contents($savefile, ' ');
            if(!$r) {
                $this->error = '文档保存失败，请检查权限！';
                return false;
            }
        }
        $savedata = array(
            'pid'=>$pid,
            'filename'=>$filename,
            'title'=>$title,
            'list_order'=>$list_order,
            'status'=>$status,
        );
        $r = $this->add($savedata);
        return $r;
    }

    //简单添加
    public function addNew($data = null)
    {
        if(!$data) $data = $_POST;
        $r = $this->add($data);
        return $r;
    }

    //修改wiki
    public function saveWiki($data = null)
    {
        if(!$data) $data = $_POST;
        $rs = $this->icheck($data);
        if(!$rs) {
            return false;
        }
        $aid = (int) $data['aid'];
        $title = trim($data['title']);
        $list_order = (int)$data['list_order'];
        $filename = trim($data['filename']);
        $content = $data['content'];
        if(empty($title)) {
            $this->error = '文档标题不能为空！';
            return false;
        }
        if($filename || $content) {
            if(empty($filename)) {
                $this->error = '文档名称不能为空！';
                return false;
            }
            if (!preg_match('/\.[a-z\d]+$/i', $filename)) {
                $filename .= $this->wiki_ext;
            }
            if($rs['filename'] && $filename != $rs['filename']) {
                $checkfile = $this->getFilePath($this->wiki_path.$filename);
                if(file_exists($checkfile)) {
                    $this->error = '保存的文档名称已存在！';
                    return false;
                }
            }
            if(empty($content)) {
                $content = ' ';
                //$this->error = '文档内容不能为空！';
                //return false;
            }
            //删除旧文档
            if($rs['filename'] && $filename != $rs['filename']) {
                $oldfile = $this->getFilePath($this->wiki_path.$rs['filename']);
                @unlink(realpath($oldfile));
            }
            $savefile = $this->getFilePath($this->wiki_path.$filename);
            $content = str_replace(array('&lt;','&gt;'), array('<', '>'), $content);
            $content = str_replace(array('&quot;'), array('"'), $content);
            $r = file_put_contents($savefile, $content);
            if(!$r) {
                $this->error = '文档保存失败，请检查权限！';
                return false;
            }
        }
        $savedata = array(
            'aid'=>$aid,
            'filename'=>$filename,
            'title'=>$title,
            'list_order'=>$list_order,
        );
        isset($data['status']) && $savedata['status'] = (int)$data['status'];
        $r = $this->save($savedata);
        return (false!==$r);
    }

    //重命名
    public function rename($data = null) {
        if(!$data) $data = $_POST;
        $rs = $this->icheck($data);
        if(!$rs) {
            return false;
        }
        if(empty($data['title'])) {
            $this->error = '标题不能为空！';
            return false;
        }
        if($data['title']==$rs['title']) {
            return true;
        }
        $savedata = array(
            'aid'=>$data['aid'],
            'title'=>$data['title'],
        );
        $r = $this->save($savedata);
        return (false!==$r);
    }

    //移动分类
    public function move($data = null) {
        if(!$data) $data = $_POST;
        $rs = $this->icheck($data);
        if(!$rs) {
            return false;
        }
        if(empty($data['aid'])) {
            $this->error = '移动的文档ID不能为空！';
            return false;
        }
        if(!is_numeric($data['pid'])) {
            $this->error = '父级分类ID不能为空！';
            return false;
        }
        $aids = $this->getIds($data['aid']);
        $savedata = array(
            'pid'=>$data['pid']
        );
        $r = $this->where(array('aid'=>array('IN',$aids)))->save($savedata);
        return (false!==$r);
    }

    //删除
    public function del($data = null) {
        if(!$data) $data = $_POST;
        if (!$data['aid']) {
            $this->error = '文档ID参数不能为空';
            return false;
        }
        $aids = $this->getIds($data['aid']);
        foreach($aids as $aid) {
            $filename = $this->where(array('aid'=>$aid))->getField('filename');
            $oldfile = $this->getFilePath($this->wiki_path.$filename);
            $filename && @unlink(realpath($oldfile)); //删除文档
            $r = $this->where(array('aid'=>array('EQ',$aid)))->delete();
            $sonIds = $this->sonIds($aid);
            if($sonIds) {
                foreach($sonIds as $aid) {
                    $filename = $this->where(array('aid'=>$aid))->getField('filename');
                    $oldfile = $this->getFilePath($this->wiki_path.$filename);
                    $filename && @unlink(realpath($oldfile)); //删除文档
                    $this->where(array('aid'=>array('EQ',$aid)))->delete();
                }
            }
        }
        if ($r) {
            return true;
        } else {
            $this->error = '删除失败';
        }
    }

    //获取子孙节点id
    public function sonIds($aid)
    {
        $ids = array();
        $list = $this->field('aid')->where(array("pid" => $aid))->select();
        if($list) {
            foreach ($list as $r) {
                $ids[] = $r['aid'];
                $r = $this->sonIds($r['aid']);
                if($r) $ids = array_merge($ids, $r);
            }
        }
        return $ids ? $ids : array();
    }

    //检测是否存在
    private function icheck($data = null) {
        if(!$data) $data = $_POST;
        $aid = $data['aid'];
        $aid && $r = $this->find($aid);
        if(!$aid || !$r) {
            $this->error = '文档不存在！';
            return false;
        }
        return $r;
    }

    //字符id转数组
    private function getIds($id) {
        $ids = explode(',', $id);
        $arr = array();
        foreach($ids as $id) {
            $id = intval(trim($id));
            if($id) $arr[] = $id;
        }
        $ids = array_unique($arr);
        return $ids;
    }

    //解决保存文件名不会乱码问题
    public function getFilePath($filepath) {
        if(IS_WIN) {
            $filepath = iconv("UTF-8", "GB2312", $filepath);
        }
        return $filepath;
    }
}